import React, { useEffect, useMemo } from 'react';
import ReactModal from 'react-modal';

import { useChangeRoute, useScrollLock } from '@/shared/lib/hooks';
import { Container, Wrapper } from '@/shared/ui';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import cs from './TopModal.module.scss';

const MobileBreakpoint = 768;

export const TopModal = ({
  isOpen,
  handleClose: handleCloseModal,
  children,
}: {
  isOpen: boolean;
  handleClose: () => void;
  children: React.ReactNode;
}) => {
  const { lock, unlock } = useScrollLock();
  const { width } = useWindowSize();
  const isMobileWidth = useMemo(() => width < MobileBreakpoint, [width]);
  const isRealOpen = useMemo(() => (!isMobileWidth ? false : isOpen), [width, isMobileWidth, isOpen]);
  const handleClose = handleCloseModal ?? (() => {});
  useChangeRoute(handleClose);
  useEffect(() => {
    if (isRealOpen) {
      lock();
      return;
    }
    handleClose();
    unlock();
  }, [isRealOpen, isOpen]);
  if (!isRealOpen) return <></>;
  return (
    <ReactModal
      ariaHideApp={false}
      className={cn(cs.modal)}
      isOpen={isOpen || false}
      onRequestClose={handleClose}
      overlayClassName={cs.container}
      preventScroll={false}
      shouldCloseOnOverlayClick
    >
      <Wrapper>
        <Container>{children}</Container>
      </Wrapper>
    </ReactModal>
  );
};
